import { editDocContent, getDocDetail } from '@/api';
import ShowEditor from '@/components/editor';
import { useDispatchDoc, useStateDocInfo } from '@/store/hooks';
import { Button, Divider, message  } from 'antd';
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';

function Editing() {
  const docInfo = useStateDocInfo()
  const location = useLocation()
  const [value,setValue] = useState('');
  const { stateSetDoc } = useDispatchDoc();
  useEffect(() => {
    var myUrl = location.search.split('=')[1] ;
    if(docInfo.content){
      setValue(docInfo.content)
    }else if(!docInfo.uuid){
      getDocDetail(myUrl).then((info:any) => {
        if (info) {
          stateSetDoc(info)
          setValue(info.content)
          window.scrollTo(0,0)
        }
      }).catch(() => {})
    }
  },[docInfo,location])
  
  const goback = ()=>{
    window.history.go(-1);
  }
  const handleSave = (status:any)=>{
    let uuid = location.search.split('=')[1] ;
    if(status===1 ){
      editDocContent(uuid,{content:value ,status:status}).then((res:any) => {
        message.success('发布成功')
        window.history.go(-1);
      }).catch(() => {})
    }else{
      editDocContent(uuid,{pre_content:value ,status:status}).then((res:any) => {
        message.success('保存成功')
      }).catch(() => {})
    }
    
  }

  return (
    <div className='editing-wrapper'>
      <div className='editing-title'>
        <h3>文档内容: </h3>
        <div>
          <Button type="primary" size='middle' onClick={()=>{handleSave(0)}}>保存草稿</Button> 
          <Button type="primary" size='middle' onClick={()=>{handleSave(1)}}>发布</Button> 
          <Button size='middle' onClick={()=>{goback()}}>返回</Button>
        </div>
      </div>
      <Divider />
      <div className='editing-editor'>
        <ShowEditor value={value} setValue={setValue} />
      </div>
    </div>
  );
}

export default Editing;
